package br.com.minhasfinancas.fw.converter;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Named;

import br.com.minhasfinancas.fw.model.AbstractModel;

@Named
public class SimpleEntityConverter implements Converter {

	protected void addAttribute(final UIComponent component, @SuppressWarnings("rawtypes") final AbstractModel o) {
		if ((o != null) && (o.getId() != null)) {
			final String key = o.getId().toString();
			this.getAttributesFrom(component).put(key, o);
		}
	}

	@Override
	public Object getAsObject(final FacesContext ctx, final UIComponent component, final String value) {
		if (value != null) {
			return this.getAttributesFrom(component).get(value);
		}
		return null;
	}

	@Override
	public String getAsString(final FacesContext ctx, final UIComponent component, final Object value) {

		if ((value != null) && !"".equals(value)) {

			@SuppressWarnings("rawtypes")
			final AbstractModel entity = (AbstractModel) value;

			// adiciona item como atributo do componente
			this.addAttribute(component, entity);

			if (entity.getId() != null) {
				return entity.getId().toString();
			}
		}

		return null;
	}

	protected Map<String, Object> getAttributesFrom(final UIComponent component) {
		return component.getAttributes();
	}

}
